
package DAO;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.*;
import DTO.Payment;
import DTO.Order;
import Exception.*;

/**
 * This class represents abstraction for data access from payment table in database.
 * This class is called from DAO as a proxy.
 * @see DAO
 * @Date Mar 30, 2011
 * @author Tony Lei
 */
public class PaymentDAO {

    private Connection conn;
    private static final Logger logger = Logger.getLogger(PaymentDAO.class.getName());

   /**
     * constructor for this class.
     * @param conn connection object
     */
    public PaymentDAO(Connection conn) {
        this.conn = conn;
    }

    /**
     * This method inserts a new payment  into database and is invoked as part of order transaction
     * @param order an order data transfer object
     * @param oid an integer order id 
     * @throws {@link KwickKioskDBException}
     */
    public void insertPayment(Order order, int oid) throws KwickKioskDBException {
        Statement sqlStatement;
        List<Payment> list = order.getPaymentList();
        try {
            sqlStatement = conn.createStatement();
            for (int i = 0; i != list.size(); i++) {
               
                String sqlText = "INSERT INTO payment "
                        + "(type, cardNo, amount, oid) VALUES ("
                        + "'" + list.get(i).getType() + "', "
                        + list.get(i).getCardNo() + ", "
                        + list.get(i).getAmount() + ", "
                        + oid + ")";
                sqlStatement.executeUpdate(sqlText);
            }
            sqlStatement.close();
            conn.commit();
        } catch (SQLException ex) {
            try {
                conn.rollback();
                logger.log(Level.SEVERE, null, "PaymentDAO : insertPayment" + ex);
                throw new KwickKioskDBException("PaymentDAO : insertPayment",
                        ex.getMessage());
            } catch (SQLException ex2) {
                logger.log(Level.SEVERE, null, "PaymentDAO : insertPayment" + ex2);
                throw new KwickKioskDBException("PaymentDAO : updateDB",
                        ex2.getMessage());
            }
        }
    }
}
